package com.sphd.emanu.activity.topupservice;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.adapter.TopupServiceAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.pojo.market.Deposit;
import com.sphd.emanu.pojo.market.Rules;
import com.sphd.emanu.utils.PermissionConfig;
import com.wzutils.BigDisMailUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 营销模块--------充值卡服务
 *
 * @Author Hu
 * @Time 2017/5/12 -- 15:23.
 * @Email 87683202@qq.com
 */
public class TopupserviceActivity extends MVPBaseActivity<TopupserviceContract.View, TopupservicePresenter> implements TopupserviceContract.View {

    @BindView(R.id.btn_new_add)
    TextView btnNewAdd;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.top_up_switch)
    Switch topUpSwitch;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    TopupServiceAdapter topupServiceAdapter;
    Intent intent;
    Bundle bundle;
    User user;
    Rules rules;
    @BindView(R.id.layout_list)
    LinearLayout layoutList;
    AlertDialog topupDialog;
    View viewDialog;
    MaterialEditText trueMoney, giveMoney;
    Button confirm, cancle;
    AndroidNextInputs inputs;
    boolean isUpdate=false;
    Deposit deposit;
    List<Moudle> moudles;
    boolean isCanDo=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topupservice);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initView() {
        setTitleBar(toolbar, "充值卡服务");
        intent = getIntent();
        bundle = intent.getExtras();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        rules = (Rules) bundle.getSerializable(Constant.RULES);

        moudles= (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo=isCanDo(moudles, PermissionConfig.MENU_MAKETING_4);
        if (!isCanDo){
            btnNewAdd.setVisibility(View.GONE);
            topUpSwitch.setEnabled(false);
        }
        topUpSwitch.setChecked(rules.getConfig().getIsDeposit());
        setRefresh(mySwf);
        setSwitch();
        initAdapter();
        initDialog();
        addData();
    }

    private void initDialog() {
        inputs = new AndroidNextInputs();
        viewDialog = View.inflate(context, R.layout.dialog_topup_edit, null);
        trueMoney = (MaterialEditText) viewDialog.findViewById(R.id.true_money);
        giveMoney = (MaterialEditText) viewDialog.findViewById(R.id.give_money);
        inputs.add(trueMoney, StaticScheme.NotBlank().msgOnFail("不能为空"), StaticScheme.Numeric().msgOnFail("请填入整数"));
        inputs.add(giveMoney, StaticScheme.NotBlank().msgOnFail("不能为空"), StaticScheme.Numeric().msgOnFail("请填入整数"));
        confirm = (Button) viewDialog.findViewById(R.id.btn_confirm);
        cancle = (Button) viewDialog.findViewById(R.id.btn_cancle);
        topupDialog = getDialogBuilder(viewDialog, R.style.AlertDialog);

    }

    private void setSwitch() {
        if (topUpSwitch.isChecked()) {
            layoutList.setVisibility(View.VISIBLE);
        } else {
            layoutList.setVisibility(View.GONE);
        }
    }

    private void addData() {
        showProgressDialog();
        mPresenter.selectDeposit(user.getOid());
    }

    private void initAdapter() {
        setRecy(myRecycler);
        topupServiceAdapter = new TopupServiceAdapter(R.layout.item_tmt_category, new ArrayList<Deposit>(),isCanDo);
        topupServiceAdapter.setEmptyView(emptyView);
        myRecycler.setAdapter(topupServiceAdapter);
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                addData();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputs.test()) {
                    // TODO: 2017/6/20 明天从这里开始
                    if (isUpdate){
                        mPresenter.updateDeposit(deposit.getId(),user.getOid(),true,
                                BigDisMailUtils.turn(trueMoney.getText().toString().trim(), Constant.POINT),
                                BigDisMailUtils.turn(giveMoney.getText().toString().trim(), Constant.POINT));
                    }else {
                        mPresenter.addDeposit(user.getOid(), true,
                                BigDisMailUtils.turn(trueMoney.getText().toString().trim(), Constant.POINT),
                                BigDisMailUtils.turn(giveMoney.getText().toString().trim(), Constant.POINT));
                    }

                } else {
                    toast("请按提示填写");
                }

            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdate){
                    isUpdate=false;
                }
            }
        });


        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                 deposit = (Deposit) adapter.getItem(position);
                trueMoney.setText(BigDisMailUtils.subZeroAndDot(deposit.getThreshold().toString()));
                giveMoney.setText(BigDisMailUtils.subZeroAndDot(deposit.getAmount().toString()));
                topupDialog.show();
                isUpdate=true;
            }

            @Override
            public void onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                super.onItemLongClick(adapter, view, position);
                new SweetAlertDialog(context,SweetAlertDialog.WARNING_TYPE).setTitleText("确认要删除吗？").setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        mPresenter.deleteDeposit(((Deposit)adapter.getItem(position)).getId(),position,sweetAlertDialog);
                    }
                }).setCancelText("取消").show();
            }
        });
        topUpSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isPressed()) {
                    mPresenter.updateIsDeposit(rules.getConfig().getId(),isChecked);
                }
            }
        });
    }

    @OnClick(R.id.btn_new_add)
    public void onViewClicked() {
        if (topupDialog != null)
            if (!topupDialog.isShowing())
                topupDialog.show();
    }

    @Override
    public void upRes(int res) {

        if (res == 1) {
            isUpdate=false;
            toast(R.string.up_success);
            if (topupDialog != null)
                if (topupDialog.isShowing())
                    topupDialog.dismiss();
            addData();
        } else {
            toast(R.string.up_failure);
        }
    }



    @Override
    public void recRes(int res) {
        if (res == 1) {
            toast(R.string.up_success);
            if (topupDialog != null)
                if (topupDialog.isShowing())
                    topupDialog.dismiss();
            addData();
        } else {
            toast(R.string.up_failure);
        }
    }

    @Override
    public void setDeposList(List<Deposit> depositList) {
        dissProgressDialog();
        topupServiceAdapter.setNewData(depositList);
    }

    @Override
    public void delRes(int res, Integer postion, SweetAlertDialog sweetAlertDialog) {
        if (res==1){
            toast(R.string.up_success);
            topupServiceAdapter.remove(postion);
            sweetAlertDialog.dismiss();
        }else {
            toast(R.string.up_failure);
        }
    }

    @Override
    public void upIsRes(int res) {
        if (res==1){
            toast(R.string.up_success);
            setSwitch();
        }else {
            toast(R.string.up_failure);
            topUpSwitch.setChecked(!topUpSwitch.isChecked());
        }
    }
}
